var handleBlog = require("./src/router/blog/index")
var handleUsers = require("./src/router/users/index")
var fs = require("fs")

module.exports= async (resquest,response)=>{
    //所有接口返回的数据都应该是一个json字符串(类似于js对象的字符串)
    //json字符串 ： '{"name":"damu","age":18}'
    //JSON.parse(json字符串) ： 将一个json字符串转为js对象
    //JSON.stringify(js对象) ： 将一个js对象转为json字符串
    response.setHeader("content-type","application/json")

    //http://127.0.0.1:8080
    var url = resquest.url; //path?query#hash
    var path = url.split("?")[0];//path
    if(path === "/"){
        var rs = fs.createReadStream("./static/index.html");
        response.setHeader("content-type","text/html")
        rs.pipe(response);
        return;
    }

    //处理blog  当blog为undefined时代表没有命中blog路由
    var blog = await handleBlog(resquest,response);
    if(blog !== undefined){
        if(blog.data === "error"){
			response.writeHead(500,blog.message);
			response.end()
		}else{
			response.end(JSON.stringify(blog));
		}
		return;
    }

    //处理用户
    var users = await handleUsers(resquest,response);
	if(users !== undefined){
		if(users.data === "error"){
			response.writeHead(500,users.message);
			response.end(JSON.stringify(users))
		}else{
		    console.log(users)
			response.end(JSON.stringify(users));
		}
		return;
	}
   
    //处理404
    response.writeHead(404,"router not found");
    response.end()
}